<?php
/**
 * Created by PhpStorm.
 * User: wumengmeng <wu_mengmeng@foxmail.com>
 * Date: 2019/4/26 0026
 * Time: 14:35
 */

namespace HiCommon\Service;

use HiCommon\Repository\UsersRepository;
use HiCommon\Repository\UsersVehicleRepository;
use Illuminate\Support\Facades\Hash;
use Modules\SmallApi\Service\FeedbackService;

class LoginUserService extends BaseService
{
    /*修改用户信息-用户手机号唯一*/
    public function api_edit_user($arr_user_data){
        $arr_user_data['id'] = intval($arr_user_data['id']);
        if($arr_user_data['id'] <= 0){
            return hello_error('用户id不能为空');
        }

        $s_phone = '';
        $arr_user_data['phone'] = isset($arr_user_data['phone']) ? str_trim($arr_user_data['phone']) : $s_phone;


        //如果用户填写了手机 要去判断手机号是否重复
        if(mb_strlen($arr_user_data['phone']) > 0){
            $arr_where = ['phone'=>$arr_user_data['phone']];
            $arr_option = ['field'=>['id','phone']];
            $result = UsersRepository::base_get_one($arr_where,$arr_option);
            if(!is_null($result)){
                $arr_user = $result->toarray();
                if($arr_user['id'] != $arr_user_data['id']){
                    return hello_error('手机号已被注册');

                }
            }
        }

        //修改用户数据
        $res = UsersRepository::base_edit_one($arr_user_data);
        if($res === false){
            return hello_error('修改失败');
        }

        return  hello_success('修改成功');
    }

    /*注册用户-用户手机号唯一*/
    public function api_register_user($arr_user_data = [], $n_invite_id = 0)
    {
        $n_invite_id = intval($n_invite_id);

        //用户默认头像
        $s_user_default_head_img = 'https://zy-mhwz.oss-cn-shanghai.aliyuncs.com/xinda/user/user_avatar.png';

        //如果是通过微信或者微信小程序注册的用户 将微信头像保存到oss
        if (strpos($arr_user_data['head_img'],'http') !== false) {
            $result = upload_wxavator_by_url($arr_user_data['head_img']);
            if ($result['state'] === 0) {
                $arr_user_data['head_img'] = $result['data']['url'];
            }
            else{
                return hello_error('获取微信头像失败，请重试');
            }
        }

        //注册
        $n_uniqid = uniqid();
        $s_username = 'xinda' . $n_uniqid;
        $s_pass = '123456';
        $s_password = Hash::make($s_pass);
        $s_nickname = '';
        $s_phone = '';
        $arr_user_data['username'] = isset($arr_user_data['username']) ? $arr_user_data['username'] : $s_username;
        $arr_user_data['head_img'] = isset($arr_user_data['head_img']) ? $arr_user_data['head_img'] : $s_user_default_head_img;
        $arr_user_data['phone'] = isset($arr_user_data['phone']) ? str_trim($arr_user_data['phone']) : $s_phone;
        $arr_user_data['nickname'] = isset($arr_user_data['nickname']) ? $arr_user_data['nickname'] : $s_nickname;
        $arr_user_data['pass'] = isset($arr_user_data['pass']) ? $arr_user_data['pass'] : $s_pass;
        $arr_user_data['password'] = isset($arr_user_data['password']) ? $arr_user_data['password'] : $s_password;
        $arr_user_data['unique_token'] = str_upper_base64_md5($s_username, 'UNIQUE');

        if(mb_strlen($arr_user_data['unionid']) > 0) {
            //微信注册
            $arr_user_data['wx_nickname'] = $arr_user_data['nickname'];
        }
        else{
            //手机号注册
            $arr_user_data['nickname'] = $arr_user_data['phone'];
        }

        $result = UsersRepository::base_add_one($arr_user_data)->toarray();
        $arr_user = $result;
        $n_uid = $arr_user['id'];
        if (empty($arr_user)) {
            return hello_error('注册失败');
        }
        $arr_user['head_img'] = $arr_user['head_img']['full_src'];

        if ($n_invite_id != 0) {
            PublicService::send_gift_invite($n_invite_id, $n_uid);
        }

        $arr_data = [
            'user' => $arr_user,
        ];

        return hello_success('注册成功', $arr_data);
    }

    /**
     * 手机验证码登录(没有就注册)-app
     *
     * @param $s_phone
     * @param $s_code
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function app_phonecode_login_or_register($s_phone, $s_code, $n_invite_id = 0)
    {
        $s_phone = str_trim($s_phone);
        $s_code = str_trim($s_code);
        if (mb_strlen($s_phone) <= 0) {
            return hello_error('手机号不能为空');
        }
        if (mb_strlen($s_phone) != 11) {
            return hello_error('手机号长度错误');
        }
        if (mb_strlen($s_code) <= 0) {
            return hello_error('验证码不能为空');
        }

        // TODO IOS包需要固定账户登录
        if($s_phone != '17721086033'){
            $s_real_code = redis_phone_code($s_phone);
            if (empty($s_real_code)) {
                return hello_error('验证码已过期');
            }
            if ($s_real_code != $s_code) {
                return hello_error('验证码错误');
            }
        }


        //验证账户
        $arr_where = [
            'phone' => $s_phone,
        ];
        $res = UsersRepository::get_one_where($arr_where);
        if (is_null($res)) {
            //用户不存在 注册新用户
            $arr_data = [
                'phone' => $s_phone,
            ];
            $result = LoginUserService::api_register_user($arr_data, $n_invite_id);
            $arr_user = $result['data']['user'];
            $n_uid = $arr_user['id'];
            if ($result['state'] != 0) {
                return $result;
            }
            $arr_input = [
                'username' => $arr_user['username'],
                'password' => $arr_user['pass']
            ];


        } else {
            //老用户 直接登录
            $arr_user = $res->toarray();
            if ($arr_user['status'] != 1) {
                return hello_error('用户已被禁用');
            }

            $arr_input = [
                'username' => str_trim($arr_user['username']),
                'password' => str_trim($arr_user['pass'])
            ];
        }

        //登录操作
        $res = self::app_attempt($arr_input);

        if ($res['state'] != 0) {
            return $res;
        }

        //销毁已使用的手机验证码
        unset_redis_phone_code($s_phone);
        return $res;
    }

    /**
     * 手机验证码登录(只登陆)-app
     *
     * @param $s_phone
     * @param $s_code
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function app_phonecode_login_direct($s_phone, $s_code)
    {

        $s_unique_token = '';

        $s_phone = str_trim($s_phone);
        $s_code = str_trim($s_code);
        if (mb_strlen($s_phone) <= 0) {
            return hello_error('手机号不能为空');
        }
        if (mb_strlen($s_phone) != 11) {
            return hello_error('手机号长度错误');
        }
        if (mb_strlen($s_code) <= 0) {
            return hello_error('验证码不能为空');
        }

          $s_real_code = redis_phone_code( $s_phone );
          if (empty($s_real_code)){
              return hello_error('验证码已过期');
          }
          if ($s_real_code != $s_code){
              return hello_error('验证码错误');
          }

        //验证账户
        $arr_where = [
            'phone' => $s_phone,
        ];
        $res = UsersRepository::get_one_where($arr_where);
        if (is_null($res)) {
            //用户不存在 注册新用户
            return hello_error('用户不存在');

        } else {
            //老用户 直接登录
            $arr_admin_user = $res->toarray();
            if ($arr_admin_user['status'] != 1) {
                return hello_error('用户已被禁用');
            }

            $arr_input = [
                'username' => str_trim($arr_admin_user['username']),
                'password' => str_trim($arr_admin_user['pass'])
            ];


        }

        //登录操作
        $res = self::app_attempt($arr_input);

        if ($res['state'] != 0) {
            return $res;
        }

        //销毁已使用的手机验证码
        unset_redis_phone_code($s_phone);
        return $res;
    }

    /**
     * 手机验证码登录-app
     *
     * @param $s_phone
     * @param $s_password
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function app_login_in($s_phone, $s_password)
    {
        $s_phone = str_trim($s_phone);
        $s_password = str_trim($s_password);
        if (mb_strlen($s_phone) <= 0) {
            return hello_error('手机号不能为空');
        }
        if (mb_strlen($s_phone) != 11) {
            return hello_error('手机号长度错误');
        }
        if (mb_strlen($s_password) <= 0) {
            return hello_error('密码不能为空');
        }

        //验证账户
        $arr_where = [
            'phone' => $s_phone,
        ];
        $res = UsersRepository::get_one_where($arr_where);
        if (is_null($res)) {
            return hello_error('用户不存在');
        }
        $arr_admin_user = $res->toarray();
        if ($arr_admin_user['status'] != 1) {
            return hello_error('用户已被禁用');
        }
        if ($arr_admin_user['pass'] != $s_password) {
            return hello_error('密码错误');
        }

        $arr_input = [
            'username' => trim((string)$arr_admin_user['username']),
            'password' => trim((string)$arr_admin_user['pass'])
        ];

        //登录操作
        $res = self::app_attempt($arr_input);
        return $res;
    }

    /**
     * 用户登录-app11
     *
     * @param array $arr_data
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function app_attempt(array $arr_data)
    {
        $s_expires_day = env('api_login_expires_day', 10);//有效天数
//        $s_expires_hour = $s_expires_day * 24;//有效小时数
//        $s_expires_in_time = 60 * $s_expires_hour;//有效分钟数

        //用户登录
        $token = api_guard()->attempt($arr_data);
        if (!$token) {
            return hello_error('登录失败', $arr_data, '登录操作失败');
        }

        //用户是否被禁用
        if (api_user()->status == 2) {
            return hello_error('微信登录失败', [], '用户账号已被禁用');
        }

        //用户基本信息
        $arr_user = api_user()->toarray();
        $arr_user = [
            'id' => $arr_user['id'],
            'username' => $arr_user['username'],
            'nickname' => $arr_user['nickname'],
            'wx_nickname' => $arr_user['wx_nickname'],
            'head_img' => oss_full_url($arr_user['head_img']),
            'email' => $arr_user['email'],
            'phone' => $arr_user['phone'],
            'sex' => $arr_user['sex'],
            'realname' => $arr_user['realname'],
            'birthday' => $arr_user['birthday'],
            'is_new_user' => $arr_user['is_new_user'],
        ];

        //查询用户默认车辆信息
        $arr_user_default_vehicle = null;
        $arr_option = [
            'where' => ['user_id' => $arr_user['id'], 'users_company_id' => 0, 'status' => 1, 'is_default' => 1],
            'field' => ['id', 'user_id', 'vehicle_model_id', 'plate_no', 'vin', 'engine_no'],
            'with' => ['simple_vehicle_model'],
        ];
        $result = UsersVehicleRepository::base_get_all($arr_option)->toarray();
        $arr_base = null;
        if (count($result) > 0) {
            $arr_user_vehicle = $result[0];
            $arr_base = $arr_user_vehicle['simple_vehicle_model'];
            $arr_base['plate_no'] = $arr_user_vehicle['plate_no'];
            $arr_base['vin'] = $arr_user_vehicle['vin'];
            $arr_base['engine_no'] = $arr_user_vehicle['engine_no'];

        }

        $arr_token = [
            'user' => $arr_user,
            'user_default_vehicle' => $arr_base,
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => api_guard()->factory()->getTTL() * $s_expires_day
        ];
        return hello_success('登录成功', $arr_token);

    }

    /**
     * 小程序微信登录
     *
     * @param $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function mini_login_in_by_jscode($arr_input)
    {

        //获取openid和用户信息
        $result = self::get_small_openid_and_mini_userinfo_by_code($arr_input, $small_user);
        if ($result['state'] != 0) {
            return $result;
        }

        //微信小程序登录
////        $openid = $small_user['openId'];
//        $s_unionid = $small_user['unionId'];
//        $s_nickname = $small_user['nickName'];
//        $s_head_img = $small_user['avatarUrl'];
//        $s_sex = $small_user['gender'];

        $arr_data = [
          'small_openid'=>$small_user['openId'],
          'unionid'=>$small_user['unionId'],
          'nickname'=>$small_user['nickName'],
          'head_img'=>$small_user['avatarUrl'],
          'sex'=>$small_user['gender'],
        ];
        $result = LoginUserService::api_wx_login($arr_data);
        return $result;

    }

    /*微信登录*/
    public function api_wx_login($data = []){
        $s_small_openid = str_trim($data['small_openid']);
        $s_unionid = str_trim($data['unionid']);
        $s_nickname = str_trim($data['nickname']);
        $s_head_img = str_trim($data['head_img']);
        $s_sex = str_trim($data['sex']);
        $s_app_openid = str_trim($data['app_openid']);
        $arr_where = [
            //            'small_openid' => $openid,
            'unionid' => $s_unionid,
        ];
        $arr_user = UsersRepository::base_get_all_by_where($arr_where)->toarray();
        $n_count_user = count($arr_user);
        if($n_count_user > 1){
            return hello_error('登录失败',[],'微信unionid有多个账号');
        }
        elseif($n_count_user == 1){

            //已注册用户，直接登录
            $arr_user = $arr_user[0];
            $s_username = $arr_user['username'];
            $s_pass = $arr_user['pass'];

            //更新小程序openid
            $arr_data = [
              'id'=>$arr_user['id'],
              'small_openid'=>$s_small_openid,
            ];
            $result = UsersRepository::base_edit_one($arr_data);
            if($result === false){
                return hello_error('登录失败',[],'小程序openid修改失败');
            }

            //登录操作
            $arr_input = [
              'username' => str_trim($s_username),
              'password' => str_trim($s_pass)
            ];
            $result = LoginUserService::app_attempt($arr_input);
            $result['data']['is_bind_phone'] = 1;

            return $result;

        }
        else{
            //未注册用户，等待填写手机号后再注册

            $arr_user = [
              'id'=>0,
              'username'=>'',
              'nickname'=>$s_nickname,
              'head_img'=>$s_head_img,
              'pass'=>'',
              'phone'=>'',
              'unionid'=>$s_unionid,
              'small_openid'=>$s_small_openid,
              'app_openid'=>$s_app_openid,
              'status'=>1,
              'sex'=>$s_sex,
            ];
            $arr_data['user'] = $arr_user;
            $arr_data['is_bind_phone'] = 2;
            return  hello_success('微信登录成功',$arr_data);

        }
    }

    /**
     * 通过code获取openid和用户信息
     *
     * @param $s_jscode
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_small_openid_and_mini_userinfo_by_code($arr_input, &$small_user)
    {
        if (empty($arr_input['code'])) {
            return hello_error('code 不能为空');
        }
        if (empty($arr_input['iv'])) {
            return hello_error('iv 不能为空');
        }
        if (empty($arr_input['encrypted_data'])) {
            return hello_error('encrypted_data 不能为空');
        }

        $s_jscode = $arr_input['code'];
        if (!$s_jscode) {
            return hello_error('code参数为null！');
        }

        //获取openid和session的地址
        //定义好的appid、appsecret等有关小程序配置的数组常量
        $wechat_data = small_wechat_congfig();
//        dd($wechat_data);
        $url = $wechat_data['url_get_openid'];
        $param = [
            'appid' => $wechat_data['app_id'],
            'secret' => $wechat_data['app_secret'],
            'js_code' => $s_jscode,
            'grant_type' => 'authorization_code',
        ];

        $url = curl_data_to_url_data($url,$param);
        $result = curl_get($url);
        $result = json_decode($result, true);
        if ($result['errcode'] != 0) {
            return hello_error($result['errmsg'], $result, $result['errcode']);
        }

        //获取用户信息


        //获取用户信息
        $encryptedData = $arr_input['encrypted_data'];
        $iv = $arr_input['iv'];
        $sessionKey = $result['session_key'];
        $openid = $result['openid'];
        $unionid = empty($result['unionid']) ? '' : $result['unionid'];
        $res = small_wechat_biz_data_crypt($sessionKey, $encryptedData, $iv, $data);
        if ($res['state'] != 0) {
            return $res;
        }
        $small_user = json_decode($data, true);
        $small_user['unionid'] = $unionid;
//        Cache::forever('session_key:'.$openid,$sessionKey);//将session_key缓存起来
        $redis_key = 'session_key:' . $openid;
        redis_string_set($redis_key, $sessionKey);
        return hello_success('成功', $small_user);
    }

    /**
     * 用户登录
     *
     * @param array $arr_data
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function mini_attempt(array $arr_data)
    {
        $s_expires_day = env('smallapi_login_expires_day', 10);//有效天数
        $s_expires_hour = $s_expires_day * 24;//有效小时数
        $s_expires_in_time = 60 * $s_expires_hour;//有效分钟数

        //用户登录
        $token = small_api_guard()->attempt($arr_data);
        if (!$token) {
            return ['state' => 1, 'msg' => '登录失败-Unauthorized', 'error' => 401, 'data' => []];
        }

        $arr_user = small_api_guard()->user()->toarray();
        $arr_user = [
            'id' => $arr_user['id'],
            'username' => $arr_user['username'],
            'nickname' => $arr_user['nickname'],
            'head_img' => $arr_user['head_img'],
            'email' => $arr_user['email'],
            'phone' => $arr_user['phone'],
            'sex' => $arr_user['sex'],
            'realname' => $arr_user['realname'],
            'birthday' => $arr_user['birthday'],
            'is_new_user' => $arr_user['is_new_user'],
        ];
        $arr_token = [
            'user' => $arr_user,
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => small_api_guard()->factory()->getTTL() * $s_expires_in_time
        ];

        if (small_api_user()->status == 2) {
            small_api_offset_user();
            return ['state' => 1, 'msg' => '账户被禁用', 'error' => '', 'data' => []];
        }
        return ['state' => 0, 'msg' => '登录成功', 'error' => '', 'data' => $arr_token];

    }

}